import { ITodoData } from "."

let todoList: ITodoData[] = []

export function addTodo(
    target: any,  // 当前装饰的函数的容器 -> TodoList.prototype
    methodName: string, // 被装饰函数的名称
    descriptor: PropertyDescriptor) // 描述我们的属性
{
    console.log(target, methodName, descriptor)
    const _origin = descriptor.value

    // 重写 addItem方法
    descriptor.value = function (todo: ITodoData) {
        const _todo: ITodoData | null = todoList.find((todoItem: ITodoData) => todoItem.content === todo.content)
        if (_todo) {
            console.log('内容重复');
        } else {
            todoList.push(todo)
            // 调用 addItem 方法
            _origin.call(this, todo)
        }
        console.log('---addTodo', todoList);
    }
  
}


export function removeTodo(
    target: any,
    methodName: string,
    descriptor: PropertyDescriptor) // 描述我们的属性
{
    console.log(target, methodName, descriptor)
    const _origin = descriptor.value

    // 重写 removeItem 方法
    descriptor.value = function (id: number, target: HTMLElement) {
        todoList = todoList.filter((todoItem: ITodoData) => todoItem.id !== id)
        // 调用 removeItem 方法
        _origin.call(this, id, target)
        console.log('---removeTodo', todoList);
    }
   
}


export function changeComplete(
    target: any,
    methodName: string,
    descriptor: PropertyDescriptor) // 描述我们的属性
{
    console.log(target, methodName, descriptor)
    const _origin = descriptor.value

    // 重写toggleComplete方法
    descriptor.value = function (id: number, target: HTMLElement) {
        todoList = todoList.map((todoItem: ITodoData) => {
            if (todoItem.id === id) {
                todoItem.completed = !todoItem.completed
                // 调用 toggleComplete 方法
                _origin.call(this, id, target)
            }
            return todoItem
        })
        console.log('---changeComplete', todoList);
    }
}
